package entity_controllers.cards;

import core.subcontrollers.PlayerController;
import ie.FieldBoard;
import ie.PlayerBoard;
import ie.Shaker;
import dto.Field;
import dto.Player;
import dto.PropertyField;
import entity_controllers.Card;

public class MoveCard extends Card {

	private int fieldIndex;
	private int moves;
	private boolean moveTo;
	
	private Class<? extends Field> fieldType;
	private boolean doubleRent = false;

	public MoveCard(String cardText, int moves) {
		super(cardText);
		this.moves = moves;
	}

	public MoveCard(String cardText, int fieldIndex, boolean moveTo) {
		super(cardText);
		this.fieldIndex = fieldIndex;
		this.moveTo = moveTo;
	}

	public MoveCard(String cardText, Class<? extends Field> fieldType) {
		super(cardText);
		this.moveTo = true;
		this.fieldType = fieldType;
	}

	public MoveCard(String cardText, Class<? extends Field> fieldType, boolean doubleRent) {
		super(cardText);
		this.moveTo = true;
		this.fieldType = fieldType;
		this.doubleRent = doubleRent;
	}

	@Override
	public void execute(Player player, FieldBoard fieldBoard, PlayerBoard playerBoard, Shaker shaker) {

		if (moveTo) {
			int currentIndex = player.getFieldIndex();

			if(fieldType != null){
				moves = findNextField(fieldBoard, fieldType, currentIndex);
			}
			else{
				if(fieldIndex > currentIndex){
					moves = fieldIndex - currentIndex;
				}
				else{
					moves = fieldBoard.getFields().length - currentIndex + fieldIndex;
				}
			}
		}

		
		// Move player 'moves' fields
		player.setDiceSum(moves);

		PlayerController.movePlayerByDiceSum(player, fieldBoard, playerBoard, shaker);
		Field field = fieldBoard.getField(player.getFieldIndex());
		if(doubleRent && field instanceof PropertyField
				&& ((PropertyField) field).getOwner() != null
				&& ((PropertyField) field).getOwner() != player){
			player.setDiceSum(0);
			PlayerController.movePlayerByDiceSum(player, fieldBoard, playerBoard, shaker);
		}
	}

	private int findNextField(FieldBoard fieldBoard, Class<? extends Field> fieldType, int currentIndex) {
		int moves = 0;
		for (int f = currentIndex+1; f < fieldBoard.getFields().length; f++) {
			moves++;
			if(fieldBoard.getField(f).getClass() == fieldType){
				return moves;
			}
		}
		for (int f = 0; f < fieldBoard.getFields().length; f++) {
			moves++;
			if(fieldBoard.getField(f).getClass() == fieldType){
				return moves;
			}
		}
		return moves;
	}

}
